<!-- QQ授权后未注册-新用户 -->
<template>
  <Form
    class="xtx-form"
    ref="target"
    :validation-schema="MySchema"
    v-slot="{ errors }"
    autocomplete="off"
  >
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-user"></i>
        <Field
          name="account"
          v-model="form.account"
          :class="{ err: errors.account }"
          class="input"
          type="text"
          placeholder="请输入用户名"
        />
      </div>
      <div v-if="errors.account" class="error">{{ errors.account }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field
          name="mobile"
          v-model="form.mobile"
          :class="{ err: errors.mobile }"
          class="input"
          type="text"
          placeholder="请输入手机号"
        />
      </div>
      <div v-if="errors.mobile" class="error">{{ errors.mobile }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field
          :class="{ err: errors.code }"
          name="code"
          v-model="form.code"
          class="input"
          type="text"
          placeholder="请输入验证码"
        />
        <span @click="send" class="code">{{ timer <= 0 ? '发送验证码' : `${timer}秒后发送` }}</span>
      </div>
      <div v-if="errors.code" class="error">{{ errors.code }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field
          :class="{ err: errors.password }"
          name="password"
          v-model="form.password"
          class="input"
          type="password"
          placeholder="请输入密码"
        />
      </div>
      <div v-if="errors.password" class="error">{{ errors.password }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field
          name="rePassword"
          v-model="form.rePassword"
          :class="{ err: errors.rePassword }"
          class="input"
          type="password"
          placeholder="请确认密码"
        />
      </div>
      <div v-if="errors.rePassword" class="error">{{ errors.rePassword }}</div>
    </div>
    <a href="javascript:;" @click="submit" class="submit">立即提交</a>
  </Form>
</template>

<script>
import QC from 'qc'
import { onUnmounted, reactive, ref } from "vue"
import { Form, Field } from "vee-validate"
import veeSchema from "@/utils/vee-validate-schema"
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { useIntervalFn } from "@vueuse/core"
import Message from '@/components/library/Message'
import { userQQPatchLogin, userQQPatchCode } from "@/api/user"

export default {
  name: 'CallbackPatch',
  components: {
    Field, Form
  },
  props: {
    openId: {
      type: String,
      required: true
    }
  },
  setup(props) {
    // 表单数据对象
    const form = reactive({
      account: null,
      mobile: null,
      code: null,
      password: null,
      rePassword: null
    })
    // 表单校验规则
    const MySchema = {
      account: veeSchema.accountApi,
      mobile: veeSchema.mobile,
      code: veeSchema.code,
      password: veeSchema.password,
      rePassword: veeSchema.rePassword
    }
    /* ============ 短信验证码登录 ============== */
    const target = ref(null)
    const timer = ref(0)
    //pause 暂停 resume 重新开始 useIntervalFn(回调函数,执行间隔,是否立即开启)
    const { pause, resume } = useIntervalFn(() => {
      timer.value--
      if (timer.value <= 0) pause()
    }, 1000, false)
    onUnmounted(() => {
      pause()
    })
    // 发送验证码
    const send = async () => {
      //验证此信息返回验证结果信息
      const valid = MySchema.mobile(form.mobile)
      // 失败时,使用vee的错误函数显示错误信息 setFieldError(字段,错误信息)
      if (valid != true) return target.value.setFieldError('mobile', valid)
      // 没有倒计时才可以发送
      if (timer.value <= 0) {
        try {
          await userQQPatchCode(form.mobile)
          Message({ type: 'success', text: '发送成功' })
          // 设置执行时长
          timer.value = 60
          resume()
        } catch (e) {
          console.dir(e)
          if (e.response && e.response.data)
            Message({ type: 'error', text: e.response.data.message || '发送失败' })
          // Message({ type: 'error', text: '发送失败' })
        }
      }
    }


    // ----------------------------------------------------------
    // 完善信息
    const store = useStore()
    const router = useRouter()
    const submit = async () => {
      const valid = await target.value.validate()
      if (valid) {
        userQQPatchLogin({
          unionId: props.openId,
          ...form
        }).then(async data => {
          // 实现和之前登录一样的逻辑
          // 1. 存储用户信息
          const { id, account, avatar, mobile, nickname, token } = data.result
          store.commit('user/setUser', { id, account, avatar, mobile, nickname, token })

          // 合并本地购物车
          await store.dispatch('cart/mergeLocalCart')
          // 2. 跳转到来源页或者首页
          router.push(store.state.user.redirectUrl)
          // 3. 成功提示
          Message({ type: 'success', text: 'QQ完善信息成功' })
        }).catch(e => {
          console.dir(e)
          if (e.response && e.response.data)
            return Message({ type: 'error', text: e.response.data.message })
          Message({ type: 'error', text: '完善信息失败' })
        })
      }
    }

    return {
      form, MySchema,
      target,
      send, timer,
      submit
    }
  }
}
</script>

<style scoped lang='less'>
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
